<template>
    <div class="default-main ba-table-box">
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />

        <!-- 表格顶部菜单 -->
        <!-- 自定义按钮请使用插槽，甚至公共搜索也可以使用具名插槽渲染，参见文档 -->
        <TableHeader
            :buttons="['refresh', 'add', 'comSearch', 'quickSearch', 'columnDisplay']"
            :quick-search-placeholder="t('Quick search placeholder', { fields: t('apply.advance.quick Search Fields') })"
        ></TableHeader>

        <!-- 表格 -->
        <!-- 表格列有多种自定义渲染方式，比如自定义组件、具名插槽等，参见文档 -->
        <!-- 要使用 el-table 组件原有的属性，直接加在 Table 标签上即可 -->
        <Table ref="tableRef"
            :show-summary="true"
            :summary-method="tableSummary"
            @selection-change="handleSelectionChange" ></Table>

        <!-- 表单 -->
        <PopupForm />
    </div>
</template>

<script setup lang="ts">
import { onMounted, provide, ref, h } from 'vue'
import { useI18n } from 'vue-i18n'
import PopupForm from './popupForm.vue'
import { baTableApi } from '/@/api/common'
import { defaultOptButtons } from '/@/components/table'
import TableHeader from '/@/components/table/header/index.vue'
import Table from '/@/components/table/index.vue'
import baTableClass from '/@/utils/baTable'
import { useAdminInfo } from '/@/stores/adminInfo'
import { advancePaid } from '/@/api/backend/index'
import { auth } from '/@/utils/common'

defineOptions({
    name: 'apply/advance',
})

const { t } = useI18n()
const tableRef = ref()
const optButtons: OptButton[] = defaultOptButtons([])
const adminInfo = useAdminInfo()

// optButtons.push({
//     render: 'confirmButton',
//     name: 'info',
//     title: '确认付款',
//     text: '确认付款',
//     type: 'success',
//     icon: '',
//     class: 'table-row-info',
//     disabledTip: false,
//     display(row, field) {
//         return auth('paid') && row.audit_state == 2 && row.paid == 1
//     },
//     click: (row: TableRow, field: TableColumn) => {
//         doPaid(row)
//     },
// })

/**
 * baTable 内包含了表格的所有数据且数据具备响应性，然后通过 provide 注入给了后代组件
 */
const baTable = new baTableClass(
    new baTableApi('/admin/apply.Advance/'),
    {
        pk: 'id',
        column: [
            { type: 'selection', align: 'center', operator: false, width: 70 },
            { label: t('apply.advance.id'), prop: 'id', align: 'center', width: 70, operator: 'RANGE', sortable: 'custom' },
            { label: t('apply.advance.no'), prop: 'no', width:'140',align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            { label: t('apply.advance.project__title'),width:'120', prop: 'project.title', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: 'custom' },
            { label: t('apply.advance.date'), prop: 'date', width:'100', align: 'center', operator: 'eq', sortable: 'custom' },
            { label: t('apply.advance.amount'),width:'100', prop: 'amount', align: 'center', operator: 'RANGE', sortable: false },
            { label: t('apply.advance.feeitem__title'), prop: 'feeitem.title',  minWidth:300, operatorPlaceholder: t('Fuzzy query'), render: 'customTemplate', operator: 'LIKE', 
                customTemplate:(row, field, value, column, index) =>{
                    let feeitems = [], html = "<div class='table-feeitem-content'>"
                    try {
                        feeitems = JSON.parse(row.feeitems)
                    } catch {
                        feeitems = []
                    }
                    feeitems.forEach((item: any) => {
                        html += `<div class="table-feeitem"><span>${item.feeitem_name}</span> <span>${ item.amount }</span></div>`
                    })
                    return html + '</div>';
                },
            },
            { label: t('apply.advance.user_name'),width:'100', prop: 'user_name', align: 'center', operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', sortable: false },
            { label: '审批状态', prop: 'audit_state', width: 110, align: 'center', operatorPlaceholder: t('Fuzzy query'), render: 'tag', operator: 'eq', replaceValue: {'0':'未提审' , '1': '审核中', '2': '审核拒绝', '3': '审核通过' }, custom: {'0':'' , '1': '', '2': 'danger', '3': 'success' }, sortable: 'custom' },
            { label: '付款状态', prop: 'paid', width: 110, align: 'center', operatorPlaceholder: t('Fuzzy query'), render: 'tag', operator: 'eq',  replaceValue: {'0':'待付款' , '1': '已付款' }, custom: { '0': 'info', '1': 'success' }, sortable: 'custom' },
            { label: t('Operate'), align: 'center', width: 100, render: 'buttons', buttons: optButtons, operator: false },
        ],
        dblClickNotEditColumn: [undefined],
        filter: {
            user_id: adminInfo.id
        },

    },
    {
        defaultItems: { date: null, amount: 0, user_id: 0, wokerflow_id: 0 },
    }
)

provide('baTable', baTable)

onMounted(() => {
    baTable.table.ref = tableRef.value
    baTable.mount()
    baTable.getIndex()?.then(() => {
        baTable.initSort()
        baTable.dragSort()
    })
})

const doPaid = (row: TableRow) => {
    advancePaid({no: row.no}).then((res: any) => {
        baTable.getIndex()
    })
}

let selDatas = []
let lastTable = 'advance'

const handleSelectionChange = (val: any[]) => {
    selDatas = val
    console.log('handleSelectionChange', val)
    // allowExport.value = val.length == 0
    let sum = 0
    let dics = {
        reimbursement: {field: 'amount', tableIndex:2, colIndex: 7},
        advance: {field: 'amount', tableIndex:3, colIndex: 5},
        payment: {field: 'pay_amount', tableIndex:4, colIndex: 7},
    }
    selDatas.forEach((item: any) => {
        sum += Number(item[dics[lastTable]['field']])
    })
    const ele = document.querySelector(`.el-table__footer-wrapper > table  tfoot > tr > td .cell .cell${dics[lastTable]['colIndex']}`)
    setTimeout(() => {
        ele.innerHTML = sum
    }, 50)
}

const tableSummary = (param: any) => {
    const { columns, data } = param
    const sums: string[] = []
    sums[0] = '合计'
    sums[5] = h('div', {class: "cell5"}, "")
    sums[6] = h('div', {class: "cell6"}, "")
    sums[7] = h('div', {class: "cell7"}, "")
    sums[8] = h('div', {class: "cell8"}, "")
    return sums
}
</script>

<style lang="scss">

</style>
